package com.ruoyi.web.sso.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.web.sso.common.util.AssertUtil;
import com.ruoyi.web.sso.common.util.BusinessException;
import com.ruoyi.web.sso.common.util.ErrorCode;
import com.ruoyi.web.sso.common.util.UuidUtil;
import com.ruoyi.web.sso.domain.*;
import com.ruoyi.web.sso.domain.DTO.AreaDTO;
import com.ruoyi.web.sso.domain.DTO.AreaListDTO;
import com.ruoyi.web.sso.domain.vo.AreaVO;
import com.ruoyi.web.sso.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.web.sso.service.IAreaService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 园所信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-03
 */
@Service
public class AreaServiceImpl implements IAreaService
{
    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private AreaStaffMapper areaStaffMapper;

    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private StaffRoleMapper staffRoleMapper;


    @Override
    public Area areaIdGetArea(String id) {
        return areaMapper.areaIdGetArea(id);
    }

    /**
     * 查询园所信息
     *
     * @param id 园所信息主键
     * @return 园所信息
     */
    @Override
    public AreaVO selectAreaById(String id)
    {
        return areaMapper.selectAreaById(id);
    }

    /**
     * 查询园所信息
     *
     * @param ids 园所信息主键
     * @return 园所信息
     */
    @Override
    public List<AreaVO> selectAreaByIds(String[] ids)
    {
        return areaMapper.selectAreaByIds(ids);
    }

    /**
     * 查询园所信息列表
     *
     * @param area 园所信息
     * @return 园所信息
     */
    @Override
    public List<AreaVO> selectAreaList(Area area)
    {
        return areaMapper.selectAreaList(area);
    }

    /**
     * 新增园所信息
     *
     * @param area 园所信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertArea(Area area)
    {
        String id = UuidUtil.getUuid();
        area.setId(id);
        area.setCreateTime(DateUtils.getNowDate());
        if (StringUtils.equals(area.getLongtitude(),"")){
            area.setLongtitude(String.valueOf(0));
        }
        if (StringUtils.equals(area.getLatitude(),"")){
            area.setLatitude(String.valueOf(0));
        }
        addAllTemplateRole(id,area.getAdminStaff());
        return areaMapper.insertArea(area);
    }

    /**
     * 修改园所信息
     *
     * @param area 园所信息
     * @return 结果
     */
    @Override
    public int updateArea(Area area)
    {
        area.setUpdateTime(DateUtils.getNowDate());
        return areaMapper.updateArea(area);
    }

    /**
     * 批量删除园所信息
     *
     * @param ids 需要删除的园所信息主键
     * @return 结果
     */
    @Override
    public int deleteAreaByIds(String ids)
    {
        return areaMapper.deleteAreaByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除园所信息信息
     *
     * @param id 园所信息主键
     * @return 结果
     */
    @Override
    public int deleteAreaById(String id)
    {
        return areaMapper.deleteAreaById(id);
    }

    @Override
    public List<Area> getAreasByStaffId(String staffId) {
        return areaMapper.getStaffIdByArea(staffId);
    }

    @Override
    @Transactional
    public AjaxResult addStaff(String areaId, String id) {
        Staff staff = staffMapper.selectStaffById(id);
        if (AssertUtil.isEmpty(staff)){
            return AjaxResult.error("手机号未注册");
        }
        //当园区是空和0时候，变成默认园区
        if (AssertUtil.isEmpty( staff.getAreaId()) || AssertUtil.isEquals(staff.getAreaId()) ){
            staff.setAreaId(areaId);
            staffMapper.updateStaff(staff);
        }
        AreaStaff areaStaff = new AreaStaff(areaId,staff.getId());
        List<AreaStaff>  list = areaStaffMapper.selectAreaStaffList(areaStaff);
        if (list.size()>0){
            return AjaxResult.error("已绑定用户");
        }
//        String roleId = roleMapper.getAreaByRoleId(areaId);
//        if (AssertUtil.isNotEmpty(roleId)){
//            areaStaff.setRoleId(roleId);
//        }
        areaStaffMapper.insertAreaStaff(areaStaff);
//        StaffRole staffRole = staffRoleMapper.selectIsExistence(new StaffRole(staff.getId(),roleId));
//        if (AssertUtil.isEmpty(staffRole)){
//            staffRoleMapper.insertStaffRole(new StaffRole(staff.getId(),roleId));
//        }
        return AjaxResult.success("添加成功");
    }

    @Override
    public List<Map<String, Object>> areaByRoleList(String id,String roleName) {
        return  areaMapper.areaByRoleList(id,roleName);
    }

    @Transactional
    public void removeAllTemplateRole(String areaId){
        Role rParam = new Role();
        rParam.setAreaId(areaId);
        List<Role> areaRoles = roleMapper.selectRoleList(rParam);

        if (areaRoles.size() > 0) {
            List<String> roleIds = areaRoles.stream().map(o -> o.getRoleId()).collect(Collectors.toList());
            roleMenuMapper.deleteByRoleIds(roleIds);
            roleMapper.deleteByRoleIds(roleIds);
        }
    }

    @Transactional
    public void addAllTemplateRole(String areaId,String adminStaffId){
        //获取所有的角色模板
        Role role = new Role();
        role.setAreaId("0");

        List<Role> roleTemplates = roleMapper.selectRoleList(role);

        for (int i = 0; i < roleTemplates.size(); i++) {
            Role template = roleTemplates.get(i);

            String templateRoleId = template.getRoleId();

            Role existRole = roleMapper.getAreaByRoleName(areaId, template.getRoleName());

            if (existRole != null){
                continue;
            }else {
                //重置id
                //用新id创建成园区角色
                String newId = UuidUtil.getUuid();
                template.setRoleId(newId);
                template.setAreaId(areaId);
                roleMapper.insertRole(template);

                //如果这个角色是园长,将创始账号设置成园长
                if (StringUtils.equals("园长", template.getRoleName())
                        && StringUtils.isNotBlank(adminStaffId)) {
                    //员工园区关系
                    areaStaffMapper.insertAreaStaff(new AreaStaff(areaId, adminStaffId, newId));

                    //员工角色
                    StaffRole staffRole = new StaffRole();
                    staffRole.setStaffId(adminStaffId);
                    staffRole.setRoleId(newId);
                    staffRoleMapper.insertStaffRole(staffRole);
                }
            }

            //找到所有角色的关联菜单
            List<RoleMenu> roleTemplateMenus = roleMenuMapper.selectRoleMenuByRoleId(templateRoleId);
            roleTemplateMenus.stream().forEach(o->{
                o.setRoleId(template.getRoleId());
            });

            if (roleTemplateMenus.size() > 0){
                roleMenuMapper.batchRoleMenu(roleTemplateMenus);
            }
        }
    }

    public int resetAreaRoleList(String areaId){
        removeAllTemplateRole(areaId);
        addAllTemplateRole(areaId, null);
        return 1;
    }


    @Override
    public Area getArea(String staffId) {
        return areaMapper.getArea(staffId);
    }

    @Override
    public List<AreaDTO> areasByLocation(float lat, float lon, Integer num) {
        return areaMapper.areasByLocation(lat,lon,num);
    }

    @Override
    public List<AreaDTO> areasByLocationLike(String pcaCode, String pcaName) {
        if (AssertUtil.isEmpty(pcaCode)){
            pcaCode = "";
        }
        if (AssertUtil.isEmpty(pcaName)){
            pcaName = "";
        }
        return areaMapper.areasByLocationLike(pcaCode,pcaName);
    }

    @Override
    public List<AreaListDTO> getInChargeArea(String staffId) {
        return areaMapper.getInChargeArea(staffId);
    }

    @Override
    public List<AreaDTO> getAllArea() {
        return areaMapper.getAllArea();
    }

    @Override
    public List<AreaDTO> getAreaName(String areaName) {
        return areaMapper.getAreaName(areaName);
    }
}
